from flask import request, jsonify, Blueprint
from models.models import User, db
import logging
from utils.jwt_util import generate_jwt_token

auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')
logger = logging.getLogger(__name__)


@auth_bp.route('/login/sms',methods=['POST'])
def login_sms():
    """
    处理手机验证码登录。
    预期请求体 JSON：
    {
        "phone_number": "手机号码",
        "code": "手机验证码"
    }
    """

    data = request.get_json()
    if not data:
        return jsonify({'message': '无效的JSON数据','status':'fail'}), 400
    
    phone_number = data.get('phone_number')
    code = data.get('code')

    if not phone_number or not code:
        return jsonify({'message': '请提供手机号码和验证码','status':'fail'}), 400
    
    #模拟验证码检查，固定为1-6
    expected_code = '123456'
    
    if code != expected_code:
        return jsonify({'message': '验证码错误','status':'fail'}), 401
    
    user = User.query.filter_by(phone_number=phone_number).first()
    token = generate_jwt_token(user.id)
    if not user:
        user = User(phone_number=phone_number)
        db.session.add(user)
        db.session.commit()
        logger.info(f'用户{phone_number}已创建')
        
        return jsonify({
        'message': '创建并登录成功',
        'token': token,
        'status':'success'
        }), 200

    return jsonify({
        'message': '登录成功',
        'token': token,
        'status':'success'
        }), 200

@auth_bp.route('/register',methods=['POST'])
def register():
    """
    处理用户注册。
    预期请求体 JSON：
    {
        "phone_number": "手机号码",
        "password": "密码"
        "code": "手机验证码"
    }
    成功则创建用户，返回用户信息。
    """

    data = request.get_json()
    if not data:
        return jsonify({'message': '无效的JSON数据','status':'fail'}), 400
    
    phone_number = data.get('phone_number')
    password = data.get('password')
    code = data.get('code')

    if not phone_number or not password or not code:
        return jsonify({'message': '请提供手机号码、密码和验证码','status':'fail'}), 400
    
    #模拟验证码检查，固定为1-6
    expected_code = '123456'
    
    if code != expected_code:
        return jsonify({'message': '验证码错误','status':'fail'}), 401
    
    user = User.query.filter_by(phone_number=phone_number).first()
    if user:
        return jsonify({'message': '用户已存在','status':'fail'}), 400
    
    user = User(phone_number=phone_number,password=password)
    user.set_password(password)
    try:
        db.session.add(user)
        db.session.commit()
        logger.info(f'用户{phone_number}已创建')
        return jsonify({
            'message': '注册成功',
            'status':'success'
            }), 201
    except Exception as e:
        #如果有异常，则回滚数据库操作
        db.session.rollback()
        logger.error(f'用户{phone_number}创建失败: {e}')

@auth_bp.route('/login/password',methods=['POST'])
def login_password():
    """
    处理密码登录。
    预期请求体 JSON：
    {
        "phone_number": "手机号码",
        "password": "密码"
    }
    """
    data = request.get_json()
    if not data:
        return jsonify({'message': '无效的JSON数据','status':'fail'}), 400
    
    phone_number = data.get('phone_number')
    password = data.get('password')
    user = User.query.filter_by(phone_number=phone_number).first()
    if not user or not user.check_password(password):
        return jsonify({'message': '用户名或密码错误','status':'fail'}), 401
    
    token = generate_jwt_token(user.id)
    return jsonify({
        'message': '登录成功',
        'token': token,
        'status':'success'
        }), 200